package com.changgou.web.seckill.aspect;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.google.common.util.concurrent.RateLimiter;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: HuangFu
 * @Date: 2020/2/24 22:07
 * @Description:
 */
@Component
@Scope
@Aspect
public class AccessLimitAop {
    @Autowired
    private HttpServletResponse httpServletResponse;

    private RateLimiter rateLimiter = RateLimiter.create(20.0);

    /**
     * 切入
     */
    @Pointcut("@annotation(com.changgou.web.seckill.aspect.AccessLimit)")
    public void limit(){}

    /**
     * 环绕通知
     */
    @Around("limit()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint){
        //执行限流
        boolean acq = rateLimiter.tryAcquire();
        Object proceed = null;
        try {
            //成功执行请求
            if(acq){
                proceed = proceedingJoinPoint.proceed();
            }else {
                outMessage(httpServletResponse, JSON.toJSONString(new Result(false, StatusCode.ERROR,"fail")));
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return proceed;
    }

    private void outMessage(HttpServletResponse response, String errorMessage) {
        ServletOutputStream outputStream = null;
        try {
            response.setContentType("application/json;charset=utf-8");
            outputStream = response.getOutputStream();
            outputStream.write(errorMessage.getBytes("UTF-8"));

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(outputStream !=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
